﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Tools;

namespace Punia
{
    [CommandAttribute(true)]
    public partial class send : BaseForm
    {
        public send(DbContext dbContext, string guid)
            : base(dbContext)
        {
            InitializeComponent();

            cbMesType.DataSource = Utility.message_types(dbContext);
            cbMesType.DisplayMember = "Name";

            lblConveration.Text = guid;
        }

        protected override void Write()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("USE [" + dbContext.Database + "];");
            sb.AppendLine();
            sb.AppendLine("BEGIN TRY");
            sb.AppendLine("   BEGIN TRANSACTION");
            sb.AppendLine("      DECLARE @ch UNIQUEIDENTIFIER");
            sb.AppendLine("      DECLARE @msg NVARCHAR(MAX);");
            sb.AppendLine();
            if (tbSend.Text != string.Empty)
                sb.AppendLine("      SET @msg = N'" + tbSend.Text + "';");

            sb.AppendLine("      SET @ch = cast('" + lblConveration.Text + "' as UNIQUEIDENTIFIER);");

            sb.AppendLine("      SEND ON CONVERSATION @ch ");
            if (cbMesType.SelectedIndex > 0)
            {
                sb.AppendLine("         MESSAGE TYPE [" + cbMesType.Text + "]");
            }

            if (tbSend.Text != string.Empty)
                sb.AppendLine("      (@msg);");

            sb.AppendLine("   COMMIT TRANSACTION");
            sb.AppendLine("END TRY");
            sb.AppendLine("BEGIN CATCH");
            sb.AppendLine("   ROLLBACK TRANSACTION;");
            sb.AppendLine("   DECLARE @m nvarchar(max)");
            sb.AppendLine("   SET @m = error_message()");
            sb.AppendLine("   RAISERROR('%s',16,1,@m)");
            sb.AppendLine("END CATCH");

            tbCommand.Text = sb.ToString();
        }

        private void cbConversation_SelectedIndexChanged(object sender, EventArgs e)
        {
            Write();
        }

        private void tbSend_TextChanged(object sender, EventArgs e)
        {
            Write();
        }

        private void cbMesType_SelectedIndexChanged(object sender, EventArgs e)
        {
            Write();
        }
    }
}